use std::str::FromStr;

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    let parts: Vec<&str> = num_str.split('(').collect();

    let origin = parts[0].trim();
    let origin = u32::from_str(origin).unwrap();

    let base = parts[1].trim().trim_end_matches(')');
    let base = u32::from_str(base).unwrap();
    println!("origin num: {}, origin base: {}", origin, base);

    let ir = match base {
        10 => origin,
        _ => convert_to_10(origin, base),
    };
    println!("num in base 10: {}", ir);

    match to_base {
        2 => format!("{:b}", ir),
        8 => format!("{:o}", ir),
        16 => format!("{:x}", ir),
        10 => ir.to_string(),
        _ => {
            let mut ret = String::new();
            let mut n = ir;
            let digits = "0123456789abcdef";

            while n > 0 {
                ret.insert(
                    0,
                    digits
                        .chars()
                        .nth((n % to_base).try_into().unwrap())
                        .unwrap(),
                );
                n /= to_base;
            }
            ret
        }
    }
}

fn convert_to_10(origin: u32, base: u32) -> u32 {
    let mut carry = 1;
    let mut ir = 0;
    let mut n = origin;
    while n > 0 {
        ir += (n % 10) * carry;
        n /= 10;
        carry *= base;
    }
    ir as u32
}
